package com.ohuang.wallpapermanager.storage.storage

import android.util.Log
import com.google.gson.reflect.TypeToken
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.adapter

class MoshiSpStorage<T : Any>(
    private var jsonAdapter: JsonAdapter<T>,
    var iStorage: SpStorage<String>,
    var defaultObject: T
) : IStorage<T> {
    override fun getValue(): T {
        if (iStorage.getValue().isEmpty()) {
            return defaultObject
        }
        return jsonAdapter.fromJson(iStorage.getValue()) ?: defaultObject
    }

    override fun setValue(value: T) {
        iStorage.setValue(jsonAdapter.toJson(value))
    }
}

@OptIn(ExperimentalStdlibApi::class)
inline fun <reified T : Any> SpStorageUtil.getForMoshi(key: String, default: T): IStorage<T> {

    val adapter = MoshiUtil.moshi.adapter<T>()

    val moshiSpStorage = MoshiSpStorage(
        jsonAdapter = adapter,
        iStorage = get<String>(key, ""),
        defaultObject = default
    )

    return moshiSpStorage
}